/**
 * Created by P0015475 on 2015/9/11.
 */

myApp.config(function ($routeProvider) {
    $routeProvider.when('/user/view', {
        templateUrl: 'user/view',
        controller: 'userListController'
    }).when('/user/addUI', {
        templateUrl: 'user/editUI',
        controller: 'userEditController'
    }).when('/user/editUI/:id', {
        templateUrl: 'user/editUI',
        controller: 'userEditController'
    });
});
myApp.service('userListService', function ($http) {
    var doRequest = function () {
        return $http.get('user/list');
    }
    return {
        userList: function () {
            return doRequest();
        }
    };
});
myApp.controller('userListController', function ($scope, $location, $http, userListService) {
    userListService.userList().success(function (response) {
        $scope.users = response;
    });
    $scope.editUI = function (id) {
        $location.path('/user/editUI/' + id);
    };
    $scope.addUI = function () {
        $location.path('/user/addUI');
    };
    $scope.deleteUser = function (id, name) {
        if (confirm('确定要删除"' + name + '"吗?')) {
            $http.get('user/delete/' + id).success(function () {
                alert('删除成功');
                userListService.userList().success(function (response) {
                    $scope.users = response;
                });
            }).error(function () {
                alert('删除失败');
            });
        }
    };
});
myApp.controller('userEditController', function ($scope, $location, $routeParams, $http) {
    if ($routeParams.id != null) {
        $http.get("user/getUser/" + $routeParams.id).success(function (response) {
            $scope.user = response;
        });
    } else {
        $scope.user = {
            sex: 1,
            roleId: 1
        };
    }


    $http.get("role/list").success(function (response) {
        $scope.roles = response;
    });
    $scope.saveUser = function () {
        $http.post('user/edit', $scope.user).success(function () {
            $location.path('/user/view');
        }).error(function () {
            alert('失败');
        });
    };
});